﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Parameters;
using System.IO;

namespace TestCrypto
{
    public enum DetailFields
    {
        Thumbprint = 0,
        Subject,
        Issuer,
        SerialNumber
    }

    public class Security
    {
        public Security()
        {

        }

        public static byte[] Sign(string text, string certSubject)
        {
            // Access Personal (MY) certificate store of current user
            X509Store store = new X509Store(StoreLocation.LocalMachine);  //  (StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            // Find the certificate we'll use to sign            
            RSACryptoServiceProvider csp = null;
            foreach (X509Certificate2 cert in store.Certificates)
            {
                if (cert.Subject.Contains(certSubject))
                {
                    // We found it. 
                    // Get its associated CSP and private key
                    csp = (RSACryptoServiceProvider)cert.PrivateKey;
                    break;
                }
            }
            if (csp == null)
            {
                throw new Exception("No valid cert was found");
            }

            string base64Encoded = EncodeTo64(text);

            // Hash the data
            SHA1Managed sha1 = new SHA1Managed();
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] data = encoding.GetBytes(base64Encoded);
            byte[] hash = sha1.ComputeHash(data);

            // Sign the hash
            return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
        }

        public static byte[] Sign(string text, DetailFields detailField, string searchPattern)
        {
            // Access Personal (MY) certificate store of current user
            X509Store store = new X509Store(StoreLocation.LocalMachine);  //  (StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection collection = store.Certificates;

            X509Certificate2 certificate = null;
            switch (detailField)
            {
                case DetailFields.SerialNumber:
                    certificate = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.SerialNumber.Equals(searchPattern, StringComparison.InvariantCultureIgnoreCase));
                    break;
                case DetailFields.Thumbprint:
                    certificate = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.Thumbprint.Equals(searchPattern, StringComparison.InvariantCultureIgnoreCase));
                    break;
                case DetailFields.Subject:
                    certificate = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.Subject.Equals(searchPattern, StringComparison.InvariantCultureIgnoreCase));
                    break;
                case DetailFields.Issuer:
                    certificate = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.Issuer.Equals(searchPattern, StringComparison.InvariantCultureIgnoreCase));
                    break;
                default:
                    break;
            }

            // Find the certificate we'll use to sign            
            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)certificate.PrivateKey;
            if (csp == null)
            {
                throw new Exception("No valid cert was found");
            }

            string base64Encoded = EncodeTo64(text);

            // Hash the data
            SHA1Managed sha1 = new SHA1Managed();
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] data = encoding.GetBytes(base64Encoded);
            byte[] hash = sha1.ComputeHash(data);

            // Sign the hash
            return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
        }

        public static bool Verify(string text, byte[] signature, string certPath)
        {
            // Load the certificate we'll use to verify the signature from a file 
            X509Certificate2 cert = new X509Certificate2(certPath);
            // Note: 
            // If we want to use the client cert in an ASP.NET app, we may use something like this instead:
            // X509Certificate2 cert = new X509Certificate2(Request.ClientCertificate.Certificate);

            // Get its associated CSP and public key
            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;

            // Hash the data
            SHA1Managed sha1 = new SHA1Managed();
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] data = encoding.GetBytes(text);
            byte[] hash = sha1.ComputeHash(data);

            // Verify the signature with the hash
            return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
        }

        public static bool VerifyFromPEM(string text, byte[] signature, string certPath)
        {
            bool retValue = false;

            try
            {
                using (FileStream fileStream = File.OpenRead(certPath))
                {
                    MemoryStream memStream = new MemoryStream();
                    memStream.SetLength(fileStream.Length);
                    fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);

                    string key = Encoding.ASCII.GetString(memStream.ToArray());

                    retValue = VerifyFromString(text, key, signature);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return retValue;
        }

        public static bool VerifyFromPEM_old(string text, byte[] signature, string certPath)
        {
            // Load the certificate we'll use to verify the signature from a file 
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter obj = ReadAsymmetricKeyParameter(certPath);

            RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)obj;

            RSAParameters rsaParameters = new RSAParameters();
            rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
            rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(rsaParameters);

            string base64Encoded = EncodeTo64(text);

            // Hash the data
            SHA1Managed sha1 = new SHA1Managed();
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] data = encoding.GetBytes(base64Encoded);
            byte[] hash = sha1.ComputeHash(data);

            // Verify the signature with the hash
            return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
        }

        public static bool VerifyFromString(string text, string theKey, byte[] signature)
        {
            bool retValue = false;

            string base64Encoded = Security.EncodeTo64(text);
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] data = encoding.GetBytes(base64Encoded);

            using (RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider())
            {
                rsaCSP.PersistKeyInCsp = false;
                rsaCSP.LoadPublicKeyPEM(theKey);
                using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
                {
                    retValue = rsaCSP.VerifyData(data, sha1, signature);
                }
            }

            return retValue;
        }

        private static Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
        {
            var fileStream = System.IO.File.OpenText(pemFilename);
            var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
            var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
            return KeyParameter;
        }

        public static string EncodeTo64(string toEncode)
        {
            byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);

            string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);

            return returnValue;
        }
    }
}
